﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ingebet.Repository.Contract;
using NHibernate;
using NHibernate.Criterion;

namespace Ingebet
{
    public class Repository<T, EntityKey> : IRepository<T, EntityKey>
    {
        public Repository()
        {
        }

        public virtual T GetByID(EntityKey id)
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            var result = s.Get<T>(id);
            return result;
        }

        public virtual IList<T> GetAll()
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            var result = s.CreateCriteria(typeof(T)).List<T>();
            return result;
        }

        public virtual void Insert(T obj)
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            s.BeginTransaction();
            s.Save(obj);
            s.Transaction.Commit();
        }

        public virtual void Insert(IList<T> o)
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            s.BeginTransaction();
            foreach (var obj in o)
            {
                s.Save(obj);
            }
            s.Transaction.Commit();
        }

        public virtual void InsertOrUpdate(T obj)
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            s.BeginTransaction();
            s.SaveOrUpdate(obj);
            s.Transaction.Commit();
        }

        public virtual void InsertOrUpdate(IList<T> o)
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            s.BeginTransaction();
            foreach (var obj in o)
            {
                s.SaveOrUpdate(obj);
            }
            s.Transaction.Commit();
        }

        public virtual void Update(T obj)
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            s.BeginTransaction();
            s.Update(obj);
            s.Transaction.Commit();
        }

        public virtual void Update(IList<T> o)
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            s.BeginTransaction();
            foreach (var obj in o)
            {
                s.Update(obj);
            }
            s.Transaction.Commit();
        }

        public virtual void Delete(T obj)
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            s.BeginTransaction();
            s.Delete(obj);
            s.Transaction.Commit();
        }

        public virtual void Delete(IList<T> o)
        {
            ISession s = HelperSessionFactory.GetCurrentSession();
            s.BeginTransaction();
            foreach (var obj in o)
            {
                s.Delete(obj);
            }
            s.Transaction.Commit();
        }
    }
}